In C++, storage classes are used to define the scope, lifetime, and initial value of variables. There are four main storage classes in C++:
int main() {
auto x = 10; // Equivalent to int x = 10;
return 0;
}
int main() {
register int count = 0; // Suggests the use of a CPU register for 'count'
return 0;
}
void increment() {
static int counter = 0; // Initialized only once
counter++;
std::cout << "Counter: " << counter << std::endl;
}
int main() {
increment(); // Counter: 1
increment(); // Counter: 2
return 0;
}
Variables declared as extern have global or external linkage, meaning they it can be accessed across multiple source files. They are typically used to declare variables that are defined in other source files.
// In File1.
int globalVar = 42;
// In File2.
extern int globalVar; // Declaration of the global variable defined in File1.
In addition to these four main storage classes, C++ also includes other storage class specifiers like mutable, which is used in the context of classes and objects to specify that a member variable it can be modified even if the object is declared as constant.
It's important to choose the appropriate storage class based on the specific requirements of program to control variable scope, lifetime, and initialization behavior. Most variables are declared without an explicit storage class specifier, which makes them automatic by default. Use static for variables that should retain their values between function calls, and use extern for global variables that need to be shared across multiple source files.
question
question2